<template>
  <div class="h-full flex flex-col repair-order-detail">
    <detail-page-header title="维修订单详情"> </detail-page-header>
    <div class="mt-[16px] h-full">
      <n-grid :col="24" x-gap="10">
        <n-grid-item span="7">
          <OrderInfo
            :repair-order-detail="repairOrderDetail"
            @update="handleUpdateOrderInfo"
          />
        </n-grid-item>
        <n-grid-item span="7">
          <n-space vertical>
            <n-card size="small">
              <span class="font-bold text-base">客户信息</span>
              <div class="mt-[16px]">
                <n-grid :cols="24" :x-gap="10" :y-gap="10">
                  <n-grid-item span="12">
                    <div class="flex items-center text-sm text-gray-500">
                      <n-icon><Person /></n-icon><span class="ml-1">姓名</span>
                    </div>
                    <div class="text-sm mt-1">
                      <span>{{ customerInfo.name }}</span>
                    </div>
                  </n-grid-item>
                  <n-grid-item span="12">
                    <div class="flex items-center text-sm text-gray-500">
                      <n-icon><PhonePortraitOutline /></n-icon
                      ><span class="ml-1">联系电话</span>
                    </div>
                    <div class="text-sm mt-1">
                      <span>{{ customerInfo.phoneNumber }}</span>
                    </div>
                  </n-grid-item>
                  <n-grid-item span="12">
                    <div class="flex items-center text-sm text-gray-500">
                      <n-icon><Mail /></n-icon><span class="ml-1">邮箱</span>
                    </div>
                    <div class="text-sm mt-1">
                      <span>{{ customerInfo.email || "/" }}</span>
                    </div>
                  </n-grid-item>
                </n-grid>
              </div>
            </n-card>
            <n-card size="small">
              <span class="font-bold text-base">内部备注</span>
              <div>
                <span class="text-xs text-gray-400"
                  >内部备注不会打印在客户凭条上</span
                >
              </div>
              <div class="pt-1">
                <n-input
                  :maxlength="2000"
                  show-count
                  type="textarea"
                  placeholder="没有前后空格"
                />
              </div>
            </n-card>
            <n-card size="small">
              <span class="font-bold text-base">维修备注</span>
              <div>
                <span class="text-xs text-gray-400"
                  >维修备注会打印在客户凭条上</span
                >
              </div>
              <div class="pt-1">
                <n-input
                  :maxlength="2000"
                  show-count
                  type="textarea"
                  placeholder="没有前后空格"
                />
              </div>
            </n-card>
          </n-space>
        </n-grid-item>
        <n-grid-item span="10" class="flex flex-col flex-1">
          <n-card size="small">
            <div class="mb-2">
              <SaleSearchProduct
                placeholder="搜索配件"
                v-model:value="searchKeyword"
                @pick-variant="handlePickVariant"
                showImeiTag
              />
            </div>
            <n-scrollbar :style="CART_LIST_CONTAINER_STYLE">
              <template v-if="shownRepairCartList.length">
                <div class="sales-cart-list">
                  <n-form size="small">
                    <n-space vertical>
                      <div
                        class="sales-cart-list__item"
                        v-for="cartItem in shownRepairCartList"
                        :key="cartItem.uuid"
                      >
                        <div class="product-name">
                          <span>{{ cartItem.name }}</span>
                          <div class="flex items-center gap-2">
                            <!-- 修改按钮 -->
                            <n-button
                              v-if="!isItemEditing(cartItem)"
                              quaternary
                              circle
                              type="primary"
                              @click.stop="handleEditItem(cartItem)"
                            >
                              <template #icon>
                                <n-icon><CreateOutline /></n-icon>
                              </template>
                            </n-button>
                            <!-- 删除按钮 -->
                            <n-popconfirm
                              @positive-click="handleRemoveCartItem(cartItem)"
                            >
                              <template #trigger>
                                <n-button quaternary circle type="primary">
                                  <template #icon>
                                    <n-icon><Trash /></n-icon>
                                  </template>
                                </n-button>
                              </template>
                              确定要移除吗？
                            </n-popconfirm>
                          </div>
                        </div>

                        <!-- 编辑状态下的表单 -->
                        <template v-if="cartItem.expand">
                          <n-grid :cols="24" x-gap="10">
                            <n-gi :span="12">
                              <n-form-item label="数量">
                                <n-input-number
                                  class="flex-1"
                                  v-model:value="cartItem.qty"
                                  :min="1"
                                  @update:value="
                                    (_:any) => handleUpdateQty(cartItem)
                                  "
                                />
                              </n-form-item>
                            </n-gi>
                            <n-gi :span="12">
                              <n-form-item label="单价">
                                <n-input v-model:value="cartItem.soldPrice" />
                              </n-form-item>
                            </n-gi>
                            <template v-if="cartItem.hasSerialNumber === '1'">
                              <n-gi
                                :span="24"
                                v-for="(imeiItem, $index) in cartItem.imeiList"
                                :key="imeiItem.uuid"
                              >
                                <n-form-item :label="`序列号${$index + 1}`">
                                  <n-input
                                    readonly
                                    clearable
                                    v-model:value="imeiItem.imei"
                                    @click.stop="
                                      handleFocusImei(
                                        imeiItem,
                                        cartItem.imeiList
                                      )
                                    "
                                  />
                                </n-form-item>
                              </n-gi>
                            </template>
                          </n-grid>

                          <!-- 编辑状态下的确认和取消按钮 -->
                          <div class="flex justify-end gap-2 mt-3">
                            <n-button
                              size="small"
                              @click.stop="handleCancelEdit(cartItem)"
                            >
                              取消
                            </n-button>
                            <n-button
                              size="small"
                              type="primary"
                              @click.stop="handleConfirmEdit(cartItem)"
                            >
                              确认
                            </n-button>
                          </div>
                        </template>

                        <!-- 非编辑状态下的显示 -->
                        <template v-else>
                          <n-grid
                            :cols="24"
                            x-gap="10"
                            @click.stop="handleClickExpend(cartItem)"
                          >
                            <template v-if="cartItem.expand">
                              <n-gi :span="12">
                                <n-form-item label="数量">
                                  <n-input-number
                                    class="flex-1"
                                    v-model:value="cartItem.qty"
                                    :min="1"
                                    @update:value="
                                      (_:any) => handleUpdateQty(cartItem)
                                    "
                                  />
                                </n-form-item>
                              </n-gi>
                              <n-gi :span="12">
                                <n-form-item label="单价">
                                  <n-input v-model:value="cartItem.soldPrice" />
                                </n-form-item>
                              </n-gi>
                              <template v-if="cartItem.hasSerialNumber === '1'">
                                <n-gi
                                  :span="24"
                                  v-for="(
                                    imeiItem, $index
                                  ) in cartItem.imeiList"
                                  :key="imeiItem.uuid"
                                >
                                  <n-form-item :label="`序列号${$index + 1}`">
                                    <n-input
                                      readonly
                                      clearable
                                      v-model:value="imeiItem.imei"
                                      @click.stop="
                                        handleFocusImei(
                                          imeiItem,
                                          cartItem.imeiList
                                        )
                                      "
                                    />
                                  </n-form-item>
                                </n-gi>
                              </template>
                            </template>
                            <template v-else>
                              <n-gi :span="12">数量: {{ cartItem.qty }}</n-gi>
                              <n-gi :span="12">
                                单价: {{ cartItem.soldPrice }}
                              </n-gi>
                            </template>
                          </n-grid>
                        </template>
                      </div>
                    </n-space>
                  </n-form>
                </div>
              </template>
              <n-empty
                v-else
                class="mt-[20vh]"
                size="large"
                description="请选择商品"
              >
              </n-empty>
            </n-scrollbar>
            <template #action>
              <div class="flex flex-row justify-between items-center">
                <span class="font-bold text-base">总成交价</span>
                <span class="font-bold text-base">
                  {{ currencyFormat(totalPrice) }}
                </span>
              </div>
            </template>
          </n-card>
        </n-grid-item>
      </n-grid>
    </div>
    <!-- 选择SN弹窗 -->
    <SaleSnModal
      v-model:show="showSaleSnModal"
      title="选择序列号"
      :variant-id="currentVariantId"
      :selectedSnId="selectedSnId"
      @pick="handlePickSN"
    />
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import Big from "big.js";
import { v4 as uuidv4 } from "uuid";
import {
  SaleSnModal,
  useSaleSnModal,
} from "@/components/biz/saleSnModal/index.ts";
import { get, debounce, isEmpty, cloneDeep } from "lodash-es";
import { SalesSearchVariantVO } from "@/types/model/sales/vos/sales.vo";
import SaleSearchProduct from "@/components/biz/saleSearchProduct/index.vue";
import {
  Person,
  PhonePortraitOutline,
  Mail,
  Trash,
  CreateOutline,
} from "@vicons/ionicons5";
import {
  getOrderDetail,
  updateRepairSalesItems,
  addRepairParts,
  updateRepairParts,
  removeRepairParts,
} from "@/api/repair/repair.api";
import { currencyFormat } from "@/common/utils/currencyFormatter/index.ts";
import { CART_LIST_CONTAINER_STYLE, CART_ITEM_ACTION_TYPE } from "./data";
import OrderInfo from "./components/orderInfo/index.vue";

const props = defineProps({
  id: {
    type: String,
    required: true,
  },
});

const { showSaleSnModal, toggleShowSaleSnModal } = useSaleSnModal();
const repairOrderDetail = ref<any>({});
const searchKeyword = ref<string>("");

const repairCartList = ref<any[]>([]);
const originRepairCartList = ref<any[]>([]);

const currentVariantId = ref<string>("");
const imeiItemUUID = ref<string>("");
const selectedSnId = ref<string[]>();

const customerInfo = computed(() => {
  return get(repairOrderDetail.value, "posCustomer") || {};
});

const totalPrice = computed(() => {
  let _total = new Big(0);
  repairCartList.value.forEach((item) => {
    if (
      item.soldPrice &&
      item.qty &&
      item.actionType !== CART_ITEM_ACTION_TYPE.DELETE
    ) {
      const _itemTotal = new Big(item.soldPrice).times(item.qty);
      _total = _total.plus(_itemTotal);
    }
  });

  return _total.toNumber();
});

const shownRepairCartList = computed(() => {
  return repairCartList.value.filter((item) => {
    return item.actionType !== CART_ITEM_ACTION_TYPE.DELETE;
  });
});

const handleConfirmEdit = async (cartItem: any) => {
  console.log("handleConfirmEdit");
  console.log(cartItem);
  let params = {
    id: props.id,
    variantId: cartItem.variantId,
    qty: cartItem.qty,
    price: cartItem.soldPrice,
    snIds: [],
  };

  if (cartItem.actionType === CART_ITEM_ACTION_TYPE.ADD) {
    await addRepairParts(params);
  } else if (cartItem.actionType === CART_ITEM_ACTION_TYPE.UPDATE) {
    await updateRepairParts(params);
  }
};

const handleEditItem = (cartItem: any) => {
  cartItem.expand = true;
  cartItem.actionType = CART_ITEM_ACTION_TYPE.UPDATE;
  console.log("handleEditItem");
  console.log(cartItem);
};

const handleCancelEdit = (cartItem: any) => {
  if (cartItem.actionType === CART_ITEM_ACTION_TYPE.UPDATE) {
    // 编辑状态，点击取消
    const id = get(cartItem, "id") || "";
    if (id) {
      const originItem = originRepairCartList.value.find(
        (item) => item.id === id
      );

      const currentCartIndex = repairCartList.value.findIndex(
        (item) => item.id === id
      );

      if (originItem && currentCartIndex > -1) {
        repairCartList.value[currentCartIndex] = cloneDeep(originItem);
        repairCartList.value[currentCartIndex].expand = false;
        repairCartList.value[currentCartIndex].actionType =
          CART_ITEM_ACTION_TYPE.VIEW;
      }
    }
  } else {
    // 新增状态，点击取消
    const uuid = get(cartItem, "uuid") || "";
    if (uuid) {
      repairCartList.value = repairCartList.value.filter(
        (item) => item.uuid !== uuid
      );
    }
  }
};

const isItemEditing = (cartItem: any) => {
  return [CART_ITEM_ACTION_TYPE.UPDATE, CART_ITEM_ACTION_TYPE.ADD].includes(
    cartItem.actionType
  );
};

const handleGetOrderDetail = (id: string) => {
  getOrderDetail({ id }).then((res) => {
    repairOrderDetail.value = get(res, "result", {}) || {};

    //  构建购物车数据
    const salesItems = get(res, "result.salesItems") || [];
    if (salesItems.length) {
      const _cartList = salesItems.map((item: any) => {
        const _itemSns = get(item, "sns") || [];
        let obj: any = {
          id: item.id,
          uuid: uuidv4(),
          variantId: item.variantId,
          variantCode: item.variantCode,
          name: item.name,
          sku: item.variantSku,
          originSoldPrice: item.originPrice,
          soldPrice: item.unitPrice,
          hasSerialNumber: item.hasSerialNumber,
          imeiList: _itemSns.map((snItem: any) => {
            return {
              variantId: item.variantId,
              uuid: uuidv4(),
              id: snItem.snId,
              imei: snItem.snName,
              available: 1,
              message: "",
              checkImeiLoading: false,
            };
          }),
          qty: item.quantity,
          expand: false,
          actionType: CART_ITEM_ACTION_TYPE.VIEW,
        };
        return obj;
      });

      repairCartList.value = cloneDeep(_cartList);
      originRepairCartList.value = cloneDeep(_cartList);
      console.log(repairCartList.value);
    }
  });
};

const handleUpdateOrderInfo = debounce(function () {
  handleGetOrderDetail(props.id);
}, 200);

const handlePickVariant = (payload: SalesSearchVariantVO) => {
  const variantId = get(payload, "id") || "";
  const hasSerialNumber = get(payload, "hasSerialNumber") || "";
  if (!variantId || !hasSerialNumber) {
    return;
  }

  let existItem: any = {};

  repairCartList.value.forEach((item) => {
    if (get(item, "variantId") === variantId) {
      existItem = item;
    }
  });

  if (isEmpty(existItem)) {
    const cartItem: any = {
      id: "",
      uuid: uuidv4(),
      variantId,
      variantCode: payload.code,
      name: payload.name,
      sku: payload.sku,
      originSoldPrice: payload.soldPrice,
      soldPrice: payload.soldPrice,
      hasSerialNumber: payload.hasSerialNumber,
      imeiList: [],
      qty: 1,
      expand: true,
      actionType: CART_ITEM_ACTION_TYPE.ADD,
    };
    if (hasSerialNumber === "1") {
      cartItem.imeiList = [createNewImeiItem(variantId)];
    }
    repairCartList.value.push(cartItem);
  } else {
    if (existItem.actionType === CART_ITEM_ACTION_TYPE.DELETE) {
      existItem.qty = 1;
      existItem.imeiList = [];
      existItem.actionType = CART_ITEM_ACTION_TYPE.UPDATE;
    } else {
      existItem.qty = existItem.qty + 1;
    }
    if (hasSerialNumber === "1") {
      existItem.imeiList.push(createNewImeiItem(variantId));
    }
    existItem.expand = true;
  }
};

const handleClickExpend = (payload: any) => {
  console.log(payload);
  const variantId = get(payload, "variantId") || "";

  for (let i = 0; i < repairCartList.value.length; i++) {
    let target = repairCartList.value[i];
    if (target.expand) {
      target.expand = false;
    }

    if (get(target, "variantId") === variantId) {
      target.expand = true;
    }
  }
};

const handleRemoveCartItem = async (payload: any) => {
  console.log("handleRemoveCartItem");
  console.log(payload);
  if (payload.actionType === CART_ITEM_ACTION_TYPE.ADD) {
    repairCartList.value = repairCartList.value.filter(
      (item) => item.uuid !== payload.uuid
    );
  } else if (
    payload.actionType === CART_ITEM_ACTION_TYPE.UPDATE ||
    payload.actionType === CART_ITEM_ACTION_TYPE.VIEW
  ) {
    // TODO: 调用删除接口
    const params = {
      id: props.id,
      salesItemId: payload.id,
    };
    await removeRepairParts(params);
  }
};

const handleUpdateQty = debounce(function (payload: any) {
  console.log(payload);
  const { qty, imeiList, hasSerialNumber, variantId } = payload;
  if (hasSerialNumber === "1") {
    let diff = qty - imeiList.length;
    if (diff > 0) {
      let diffImeiList = [];
      for (let i = 0; i < diff; i++) {
        diffImeiList.push(createNewImeiItem(variantId));
      }
      imeiList.push(...diffImeiList);
    } else if (diff < 0) {
      // 从尾部开始删除
      for (let i = 0; i < Math.abs(diff); i++) {
        imeiList.pop();
      }
    }
  }
}, 200);

const handleFocusImei = (payload: any, imeiList: any[]) => {
  console.log(payload);
  currentVariantId.value = payload.variantId;
  imeiItemUUID.value = payload.uuid;
  let _selectedSnIds: string[] = [];
  imeiList.forEach((item) => {
    if (item.id) {
      _selectedSnIds.push(item.id);
    }
  });
  selectedSnId.value = _selectedSnIds;
  console.log(selectedSnId.value);
  toggleShowSaleSnModal(true);
};

const createNewImeiItem = (variantId: string, imei: string = "") => {
  return {
    checkImeiLoading: false,
    id: "",
    variantId: variantId,
    uuid: uuidv4(),
    imei: imei,
    available: -1,
    message: "",
  };
};

const handlePickSN = (payload: any) => {
  const targetCartItem =
    repairCartList.value.find(
      (item) => item.variantId === currentVariantId.value
    ) || {};
  if (!isEmpty(targetCartItem)) {
    const targetImeiItem =
      targetCartItem.imeiList.find(
        (item: any) => item.uuid === imeiItemUUID.value
      ) || {};
    if (!isEmpty(targetImeiItem)) {
      const { id, name } = payload;
      targetImeiItem.id = id;
      targetImeiItem.imei = name;
    }
  }
};

const handleSubmit = () => {
  let _deleteCartItems: any[] = [];
  let _addCartItems: any[] = [];
  let _updateCartItems: any[] = [];

  repairCartList.value.forEach((item) => {
    let cloneItem = cloneDeep(item);
    // 映射序列号ID列表
    cloneItem.snIds = cloneItem.imeiList.map((item: any) => item.id);

    // 添加缺失的 productId 字段
    cloneItem.productId = repairOrderDetail.value?.repair?.productId;

    // 确保所有必需字段都存在
    const salesItem = {
      id: cloneItem.id,
      productId: cloneItem.productId,
      variantId: cloneItem.variantId,
      variantCode: cloneItem.variantCode,
      name: cloneItem.name,
      hasSerialNumber: cloneItem.hasSerialNumber,
      originSoldPrice: cloneItem.originSoldPrice,
      soldPrice: cloneItem.soldPrice,
      qty: cloneItem.qty,
      snIds: cloneItem.snIds,
    };

    if (item.actionType === CART_ITEM_ACTION_TYPE.DELETE) {
      _deleteCartItems.push(salesItem);
    } else if (item.actionType === CART_ITEM_ACTION_TYPE.ADD) {
      _addCartItems.push(salesItem);
    } else if (item.actionType === CART_ITEM_ACTION_TYPE.UPDATE) {
      _updateCartItems.push(salesItem);
    }
  });

  const params = {
    id: repairOrderDetail.value?.repair?.id,
    deleteItems: _deleteCartItems,
    addItems: _addCartItems,
    updateItems: _updateCartItems,
  };

  console.log("提交参数:", params);

  // 添加错误处理
  updateRepairSalesItems(params)
    .then((result) => {
      console.log("更新成功:", result);
      // 可以添加成功提示
      // message.success('维修项目更新成功');
      // 重新获取订单详情
      handleGetOrderDetail(props.id);
    })
    .catch((error) => {
      console.error("更新失败:", error);
      // 可以添加错误提示
      // message.error('维修项目更新失败');
    });
};

const init = () => {
  if (props.id) {
    handleGetOrderDetail(props.id);
  }
};

onMounted(() => init());
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
